package com.etc.test;

import java.util.Random;

public class TicketRunnable implements Runnable {

    // 卖100张
    private int ticketCount = 100;

    // 定义一个方法执行卖票的操作 =>synchronized
    private synchronized void saleTicket() {
        // 判断一下
        //
        if (ticketCount > 0) {
            // Thread.currentThread() 线程对象
            Thread th = Thread.currentThread();
            // ticketCount-- 每次--
            System.out.println(th.getId() + "," + th.getName() + "正在卖第" + ticketCount-- + "张卖票");

            // 每次卖票需要花费一定的时间
            try {
                Thread.sleep(new Random().nextInt(30));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        // 调用saleTicket方法
        while (ticketCount > 0) {
            saleTicket();
        }
    }

}